package javolution.xml.stream;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import javax.realtime.MemoryArea;
import javolution.context.ObjectFactory;
import javolution.io.UTF8StreamWriter;
import javolution.lang.Reusable;
import javolution.text.CharArray;
import javolution.text.TextBuilder;
import kotlin.text.Typography;
import org.apache.http.protocol.HTTP;

/* loaded from: classes2.dex */
public final class XMLStreamWriterImpl implements XMLStreamWriter, Reusable {
    private static final int BUFFER_LENGTH = 2048;
    private int _autoNSCount;
    private boolean _automaticEmptyElements;
    private String _encoding;
    private String _indentation;
    private int _indentationLevel;
    private int _index;
    private boolean _isElementOpen;
    private boolean _isEmptyElement;
    private boolean _isRepairingNamespaces;
    ObjectFactory _objectFactory;
    private Writer _writer;
    private int _nesting = 0;
    private TextBuilder[] _qNames = new TextBuilder[16];
    private final char[] _buffer = new char[2048];
    private final NamespacesImpl _namespaces = new NamespacesImpl();
    private String _repairingPrefix = "ns";
    private final UTF8StreamWriter _utf8StreamWriter = new UTF8StreamWriter();
    private final CharArray _noChar = new CharArray("");
    private final TextBuilder _autoPrefix = new TextBuilder();

    public XMLStreamWriterImpl() {
        int i = 0;
        while (true) {
            TextBuilder[] textBuilderArr = this._qNames;
            if (i >= textBuilderArr.length) {
                return;
            }
            textBuilderArr[i] = new TextBuilder();
            i++;
        }
    }

    private void closeOpenTag() throws XMLStreamException {
        writeNamespaces();
        this._isElementOpen = false;
        if (!this._isEmptyElement) {
            write(Typography.greater);
            return;
        }
        write('/');
        write(Typography.greater);
        this._nesting--;
        this._namespaces.pop();
        this._isEmptyElement = false;
    }

    private void flushBuffer() throws XMLStreamException {
        try {
            try {
                this._writer.write(this._buffer, 0, this._index);
            } catch (IOException e) {
                throw new XMLStreamException(e);
            }
        } finally {
            this._index = 0;
        }
    }

    private CharSequence getRepairedPrefix(CharSequence charSequence, CharSequence charSequence2) throws XMLStreamException {
        CharArray prefix = this._namespaces.getPrefix(charSequence2);
        if (prefix == null || !(charSequence == null || prefix.equals((Object) charSequence))) {
            if (charSequence == null || charSequence.length() == 0) {
                TextBuilder append = this._autoPrefix.clear().append(this._repairingPrefix);
                int i = this._autoNSCount;
                this._autoNSCount = i + 1;
                charSequence = append.append(i);
            }
            this._namespaces.setPrefix(charSequence, charSequence2, true);
            return charSequence;
        }
        return prefix;
    }

    private void resizeElemStack() {
        MemoryArea.getMemoryArea(this).executeInArea(new Runnable() { // from class: javolution.xml.stream.XMLStreamWriterImpl.1
            @Override // java.lang.Runnable
            public void run() {
                int length = XMLStreamWriterImpl.this._qNames.length;
                int i = length * 2;
                TextBuilder[] textBuilderArr = new TextBuilder[i];
                System.arraycopy(XMLStreamWriterImpl.this._qNames, 0, textBuilderArr, 0, length);
                XMLStreamWriterImpl.this._qNames = textBuilderArr;
                while (length < i) {
                    XMLStreamWriterImpl.this._qNames[length] = new TextBuilder();
                    length++;
                }
            }
        });
    }

    private final void write(char c) throws XMLStreamException {
        char[] cArr = this._buffer;
        int i = this._index;
        this._index = i + 1;
        cArr[i] = c;
        if (this._index == 2048) {
            flushBuffer();
        }
    }

    private void write(Object obj) throws XMLStreamException {
        if (obj instanceof String) {
            writeStr((String) obj);
        } else {
            writeCsq((CharSequence) obj);
        }
    }

    private void writeAttributeOrNamespace(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3, CharSequence charSequence4) throws XMLStreamException {
        if (!this._isElementOpen) {
            throw new IllegalStateException("No open start element");
        }
        write(' ');
        if (charSequence2 != null && !this._namespaces._defaultNamespace.equals((Object) charSequence2)) {
            if (this._isRepairingNamespaces) {
                charSequence = getRepairedPrefix(charSequence, charSequence2);
            } else if (charSequence == null && (charSequence = getPrefix(charSequence2)) == null) {
                throw new XMLStreamException("URI: " + ((Object) charSequence2) + " not bound and repairing namespaces disabled");
            }
            if (charSequence.length() > 0) {
                write(charSequence);
                write(':');
            }
        }
        write(charSequence3);
        write('=');
        write(Typography.quote);
        writeEsc(charSequence4);
        write(Typography.quote);
    }

    private void writeCsq(CharSequence charSequence) throws XMLStreamException {
        int length = charSequence.length();
        int i = 0;
        while (i < length) {
            char[] cArr = this._buffer;
            int i2 = this._index;
            this._index = i2 + 1;
            int i3 = i + 1;
            cArr[i2] = charSequence.charAt(i);
            if (this._index == 2048) {
                flushBuffer();
            }
            i = i3;
        }
    }

    private final void writeEsc(char c) throws XMLStreamException {
        if (c >= '?' || !(c < ' ' || c == '<' || c == '>' || c == '\"' || c == '&')) {
            write(c);
        } else {
            writeEsc2(c);
        }
    }

    private void writeEsc(Object obj) throws XMLStreamException {
        if (obj instanceof String) {
            writeEscStr((String) obj);
        } else {
            writeEscCsq((CharSequence) obj);
        }
    }

    private final void writeEsc2(char c) throws XMLStreamException {
        String str;
        if (c == '\"') {
            str = "&quot;";
        } else if (c == '&') {
            str = "&amp;";
        } else if (c == '<') {
            str = "&lt;";
        } else if (c != '>') {
            if (c < ' ') {
                writeStr("&#");
                write((char) ((c / '\n') + 48));
                write((char) ((c % '\n') + 48));
                c = ';';
            }
            write(c);
            return;
        } else {
            str = "&gt;";
        }
        writeStr(str);
    }

    private void writeEscCsq(CharSequence charSequence) throws XMLStreamException {
        int length = charSequence.length();
        int i = 0;
        while (i < length) {
            int i2 = i + 1;
            char charAt = charSequence.charAt(i);
            if (charAt >= '?' || !(charAt < ' ' || charAt == '<' || charAt == '>' || charAt == '\"' || charAt == '&')) {
                char[] cArr = this._buffer;
                int i3 = this._index;
                this._index = i3 + 1;
                cArr[i3] = charAt;
                if (this._index == 2048) {
                    flushBuffer();
                }
            } else {
                writeEsc2(charAt);
            }
            i = i2;
        }
    }

    private void writeEscStr(String str) throws XMLStreamException {
        int length = str.length();
        int i = 0;
        while (i < length) {
            int i2 = i + 1;
            char charAt = str.charAt(i);
            if (charAt >= '?' || !(charAt < ' ' || charAt == '<' || charAt == '>' || charAt == '\"' || charAt == '&')) {
                char[] cArr = this._buffer;
                int i3 = this._index;
                this._index = i3 + 1;
                cArr[i3] = charAt;
                if (this._index == 2048) {
                    flushBuffer();
                }
            } else {
                writeEsc2(charAt);
            }
            i = i2;
        }
    }

    private void writeNamespaces() throws XMLStreamException {
        int i = this._namespaces._namespacesCount[this._nesting - 1];
        int i2 = this._namespaces._namespacesCount[this._nesting];
        for (int i3 = this._nesting > 1 ? this._namespaces._namespacesCount[this._nesting - 2] : 3; i3 < i2; i3++) {
            if ((this._isRepairingNamespaces && i3 < i && !this._namespaces._prefixesWritten[i3]) || (i3 >= i && this._namespaces._prefixesWritten[i3])) {
                if (this._isRepairingNamespaces) {
                    NamespacesImpl namespacesImpl = this._namespaces;
                    if (this._namespaces._prefixes[i3].equals(namespacesImpl.getPrefix(namespacesImpl._namespaces[i3], i3))) {
                    }
                }
                if (this._namespaces._prefixes[i3].length() == 0) {
                    writeAttributeOrNamespace(null, null, this._namespaces._xmlns, this._namespaces._namespaces[i3]);
                } else {
                    writeAttributeOrNamespace(this._namespaces._xmlns, this._namespaces._xmlnsURI, this._namespaces._prefixes[i3], this._namespaces._namespaces[i3]);
                }
            }
        }
    }

    private void writeNewElement(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3) throws XMLStreamException {
        if (this._isElementOpen) {
            closeOpenTag();
        }
        if (this._indentation != null) {
            write('\n');
            this._indentationLevel = this._nesting;
            for (int i = 0; i < this._indentationLevel; i++) {
                writeStr(this._indentation);
            }
        }
        write(Typography.less);
        this._isElementOpen = true;
        int i2 = this._nesting + 1;
        this._nesting = i2;
        if (i2 >= this._qNames.length) {
            resizeElemStack();
        }
        this._namespaces.push();
        TextBuilder clear = this._qNames[this._nesting].clear();
        if (charSequence3 != null && !this._namespaces._defaultNamespace.equals((Object) charSequence3)) {
            if (this._isRepairingNamespaces) {
                charSequence = getRepairedPrefix(charSequence, charSequence3);
            } else if (charSequence == null && (charSequence = getPrefix(charSequence3)) == null) {
                throw new XMLStreamException("URI: " + ((Object) charSequence3) + " not bound and repairing namespaces disabled");
            }
            if (charSequence.length() > 0) {
                clear.append(charSequence);
                clear.append(':');
            }
        }
        clear.append(charSequence2);
        writeTB(clear);
    }

    private void writeStr(String str) throws XMLStreamException {
        int length = str.length();
        int i = this._index;
        if (i + length >= 2048) {
            writeStrImmediate(str);
            return;
        }
        str.getChars(0, length, this._buffer, i);
        this._index += length;
    }

    private void writeStrImmediate(String str) throws XMLStreamException {
        flushBuffer();
        try {
            this._writer.write(str);
        } catch (IOException e) {
            throw new XMLStreamException(e);
        }
    }

    private void writeTB(TextBuilder textBuilder) throws XMLStreamException {
        int length = textBuilder.length();
        int i = 0;
        while (i < length) {
            char[] cArr = this._buffer;
            int i2 = this._index;
            this._index = i2 + 1;
            int i3 = i + 1;
            cArr[i2] = textBuilder.charAt(i);
            if (this._index == 2048) {
                flushBuffer();
            }
            i = i3;
        }
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void close() throws XMLStreamException {
        if (this._writer != null) {
            if (this._nesting != 0) {
                writeEndDocument();
            }
            flush();
        }
        ObjectFactory objectFactory = this._objectFactory;
        if (objectFactory != null) {
            objectFactory.recycle(this);
        } else {
            reset();
        }
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void flush() throws XMLStreamException {
        flushBuffer();
        try {
            this._writer.flush();
        } catch (IOException e) {
            throw new XMLStreamException(e);
        }
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public CharSequence getPrefix(CharSequence charSequence) throws XMLStreamException {
        return this._namespaces.getPrefix(charSequence);
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public Object getProperty(String str) throws IllegalArgumentException {
        if (str.equals(XMLOutputFactory.IS_REPAIRING_NAMESPACES)) {
            return new Boolean(this._isRepairingNamespaces);
        }
        if (str.equals(XMLOutputFactory.REPAIRING_PREFIX)) {
            return this._repairingPrefix;
        }
        if (str.equals(XMLOutputFactory.AUTOMATIC_EMPTY_ELEMENTS)) {
            return new Boolean(this._automaticEmptyElements);
        }
        if (str.equals(XMLOutputFactory.INDENTATION)) {
            return this._indentation;
        }
        throw new IllegalArgumentException("Property: " + str + " not supported");
    }

    @Override // javolution.lang.Reusable
    public void reset() {
        this._automaticEmptyElements = false;
        this._autoNSCount = 0;
        this._encoding = null;
        this._indentation = null;
        this._indentationLevel = 0;
        this._index = 0;
        this._isElementOpen = false;
        this._isEmptyElement = false;
        this._isRepairingNamespaces = false;
        this._namespaces.reset();
        this._nesting = 0;
        this._objectFactory = null;
        this._repairingPrefix = "ns";
        this._utf8StreamWriter.reset();
        this._writer = null;
    }

    public void setAutomaticEmptyElements(boolean z) {
        this._automaticEmptyElements = z;
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void setDefaultNamespace(CharSequence charSequence) throws XMLStreamException {
        setPrefix(this._namespaces._defaultNsPrefix, charSequence);
    }

    public void setIndentation(String str) {
        this._indentation = str;
    }

    public void setOutput(OutputStream outputStream) throws XMLStreamException {
        this._utf8StreamWriter.setOutput(outputStream);
        this._encoding = "UTF-8";
        setOutput(this._utf8StreamWriter);
    }

    public void setOutput(OutputStream outputStream, String str) throws XMLStreamException {
        if (str.equals("UTF-8") || str.equals("utf-8") || str.equals(HTTP.ASCII)) {
            setOutput(outputStream);
            return;
        }
        try {
            this._encoding = str;
            setOutput(new OutputStreamWriter(outputStream, str));
        } catch (UnsupportedEncodingException e) {
            throw new XMLStreamException(e);
        }
    }

    public void setOutput(Writer writer) throws XMLStreamException {
        if (this._writer != null) {
            throw new IllegalStateException("Writer not closed or reset");
        }
        this._writer = writer;
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void setPrefix(CharSequence charSequence, CharSequence charSequence2) throws XMLStreamException {
        NamespacesImpl namespacesImpl = this._namespaces;
        if (charSequence2 == null) {
            charSequence2 = namespacesImpl._nullNsURI;
        }
        namespacesImpl.setPrefix(charSequence, charSequence2, false);
    }

    public void setRepairingNamespaces(boolean z) {
        this._isRepairingNamespaces = z;
    }

    public void setRepairingPrefix(String str) {
        this._repairingPrefix = str;
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeAttribute(CharSequence charSequence, CharSequence charSequence2) throws XMLStreamException {
        if (charSequence == null) {
            throw new XMLStreamException("Local name cannot be null");
        }
        if (charSequence2 == null) {
            throw new XMLStreamException("Value cannot be null");
        }
        writeAttributeOrNamespace(null, null, charSequence, charSequence2);
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeAttribute(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3) throws XMLStreamException {
        if (charSequence2 == null) {
            throw new XMLStreamException("Local name cannot be null");
        }
        if (charSequence3 == null) {
            throw new XMLStreamException("Value cannot be null");
        }
        if (charSequence == null) {
            throw new XMLStreamException("Namespace URI cannot be null");
        }
        writeAttributeOrNamespace(null, charSequence, charSequence2, charSequence3);
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeAttribute(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3, CharSequence charSequence4) throws XMLStreamException {
        if (charSequence3 == null) {
            throw new XMLStreamException("Local name cannot be null");
        }
        if (charSequence4 == null) {
            throw new XMLStreamException("Value cannot be null");
        }
        if (charSequence2 == null) {
            throw new XMLStreamException("Namespace URI cannot be null");
        }
        if (charSequence == null) {
            throw new XMLStreamException("Prefix cannot be null");
        }
        writeAttributeOrNamespace(charSequence, charSequence2, charSequence3, charSequence4);
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeCData(CharSequence charSequence) throws XMLStreamException {
        if (charSequence == null) {
            throw new XMLStreamException("Data cannot be null");
        }
        if (this._isElementOpen) {
            closeOpenTag();
        }
        writeStr("<![CDATA[");
        write(charSequence);
        writeStr("]]>");
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeCharacters(CharSequence charSequence) throws XMLStreamException {
        if (this._isElementOpen) {
            closeOpenTag();
        }
        if (charSequence == null) {
            return;
        }
        writeEsc(charSequence);
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeCharacters(char[] cArr, int i, int i2) throws XMLStreamException {
        int i3 = i2 + i;
        while (i < i3) {
            writeEsc(cArr[i]);
            i++;
        }
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeComment(CharSequence charSequence) throws XMLStreamException {
        if (this._isElementOpen) {
            closeOpenTag();
        }
        writeStr("<!--");
        if (charSequence != null) {
            write(charSequence);
        }
        writeStr("-->");
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeDTD(CharSequence charSequence) throws XMLStreamException {
        if (charSequence == null) {
            throw new XMLStreamException("DTD cannot be null");
        }
        if (this._nesting > 0) {
            throw new XMLStreamException("DOCTYPE declaration (DTD) when not in document root (prolog)");
        }
        write(charSequence);
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeDefaultNamespace(CharSequence charSequence) throws XMLStreamException {
        writeNamespace(this._namespaces._defaultNsPrefix, charSequence);
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeEmptyElement(CharSequence charSequence) throws XMLStreamException {
        writeStartElement(charSequence);
        this._isEmptyElement = true;
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeEmptyElement(CharSequence charSequence, CharSequence charSequence2) throws XMLStreamException {
        writeStartElement(charSequence, charSequence2);
        this._isEmptyElement = true;
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeEmptyElement(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3) throws XMLStreamException {
        writeStartElement(charSequence, charSequence2, charSequence3);
        this._isEmptyElement = true;
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeEndDocument() throws XMLStreamException {
        if (this._isElementOpen) {
            closeOpenTag();
        }
        while (this._nesting > 0) {
            writeEndElement();
        }
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeEndElement() throws XMLStreamException {
        if (this._isElementOpen) {
            if (this._automaticEmptyElements) {
                this._isEmptyElement = true;
                closeOpenTag();
                return;
            }
            closeOpenTag();
        }
        if (this._indentation != null && this._indentationLevel != this._nesting - 1) {
            write('\n');
            for (int i = 1; i < this._nesting; i++) {
                writeStr(this._indentation);
            }
        }
        write(Typography.less);
        write('/');
        TextBuilder[] textBuilderArr = this._qNames;
        int i2 = this._nesting;
        this._nesting = i2 - 1;
        writeTB(textBuilderArr[i2]);
        write(Typography.greater);
        this._namespaces.pop();
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeEntityRef(CharSequence charSequence) throws XMLStreamException {
        write(Typography.amp);
        write(charSequence);
        write(';');
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeNamespace(CharSequence charSequence, CharSequence charSequence2) throws XMLStreamException {
        if (charSequence == null || charSequence.length() == 0 || this._namespaces._xmlns.equals((Object) charSequence)) {
            charSequence = this._namespaces._defaultNsPrefix;
        }
        if (!this._isElementOpen) {
            throw new IllegalStateException("No open start element");
        }
        NamespacesImpl namespacesImpl = this._namespaces;
        if (charSequence2 == null) {
            charSequence2 = namespacesImpl._nullNsURI;
        }
        namespacesImpl.setPrefix(charSequence, charSequence2, true);
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeProcessingInstruction(CharSequence charSequence) throws XMLStreamException {
        writeProcessingInstruction(charSequence, this._noChar);
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeProcessingInstruction(CharSequence charSequence, CharSequence charSequence2) throws XMLStreamException {
        if (charSequence == null) {
            throw new XMLStreamException("Target cannot be null");
        }
        if (charSequence2 == null) {
            throw new XMLStreamException("Data cannot be null");
        }
        if (this._isElementOpen) {
            closeOpenTag();
        }
        writeStr("<?");
        write(charSequence);
        write(' ');
        write(charSequence2);
        write(" ?>");
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeStartDocument() throws XMLStreamException {
        writeStartDocument(null, null);
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeStartDocument(CharSequence charSequence) throws XMLStreamException {
        writeStartDocument(null, charSequence);
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeStartDocument(CharSequence charSequence, CharSequence charSequence2) throws XMLStreamException {
        if (this._nesting > 0) {
            throw new XMLStreamException("Not in document root");
        }
        writeStr("<?xml version=\"");
        if (charSequence2 != null) {
            write(charSequence2);
            write(Typography.quote);
        } else {
            writeStr("1.0\"");
        }
        if (charSequence == null) {
            if (this._encoding != null) {
                writeStr(" encoding=\"");
                writeStr(this._encoding);
            }
            writeStr(" ?>");
        }
        writeStr(" encoding=\"");
        write(charSequence);
        write(Typography.quote);
        writeStr(" ?>");
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeStartElement(CharSequence charSequence) throws XMLStreamException {
        if (charSequence == null) {
            throw new XMLStreamException("Local name cannot be null");
        }
        writeNewElement(null, charSequence, null);
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeStartElement(CharSequence charSequence, CharSequence charSequence2) throws XMLStreamException {
        if (charSequence2 == null) {
            throw new XMLStreamException("Local name cannot be null");
        }
        if (charSequence == null) {
            throw new XMLStreamException("Namespace URI cannot be null");
        }
        writeNewElement(null, charSequence2, charSequence);
    }

    @Override // javolution.xml.stream.XMLStreamWriter
    public void writeStartElement(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3) throws XMLStreamException {
        if (charSequence2 == null) {
            throw new XMLStreamException("Local name cannot be null");
        }
        if (charSequence3 == null) {
            throw new XMLStreamException("Namespace URI cannot be null");
        }
        if (charSequence == null) {
            throw new XMLStreamException("Prefix cannot be null");
        }
        writeNewElement(charSequence, charSequence2, charSequence3);
    }
}
